import React, { PureComponent } from 'react';
import { Table, Form } from 'antd';
import { connect } from 'dva';
import styles from './index.less';
import EditableCell, { EditableContext } from './EditableCell';
import { timeFormat } from '@/utils/common';
import request from '@/utils/request';
import { eventBus } from '@/utils/event';

const pageBaseConifg = {
  showQuickJumper: true,
  // showpageSizeChanger: true,
  showTotal: (total) => `共${total}条`,
};
const COLUMN_ORDER = {
  title: '序号',
  key: 'order',
  width: 60,
  render: (text, record, index) => index + 1,
};

@connect((state) => state.base)
// @Form.create()
class TableList extends PureComponent {
  static defaultProps = {
    // 是否初始化数据
    initialData: true,
    // 是否展示序号
    showOrder: false,
    // 表格行 key 的取值，可以是字符串或一个函数
    rowKey: 'id',
    // post请求
    post: false,
    pageNum: 1,
    pageSize: 10,
    // 设置列的对齐方式
    align: 'center',
    onRef: () => {},
    tableProps: {},
    autoFetch: true, //是否默认进行第一次请求
  };

  state = {
    loading: false,
    // 表格数据
    dataSource: [],
    // 搜索条件
    params: {
      // 当前页
      pageNum: this.props.pageNum,
      // 每页条数
      pageSize: this.props.pageSize,
      // 有可能会有些数据需要外面传进来的
      ...this.props.params,
    },
    pagination: {
      current: this.props.pageNum,
      pageSize: this.props.pageSize,
      total: 0,
      ...pageBaseConifg,
    },
    handleTableChange: (pagination) => {
      this.setState(
        (prevState) => ({
          params: {
            ...prevState.params,
            pageNum: pagination.current,
            pageSize: pagination.pageSize,
          },
          pagination,
        }),
        () => {
          if (this.props.onChange) {
            this.props.onChange(pagination);
          }
          this.fetch(this.state.params);
        },
      );
    },
  };

  componentDidMount() {
    this.props.onRef(this);
    const { autoFetch, initialData } = this.props;
    if (initialData && autoFetch) {
      this.fetch(this.state.params);
    }
    eventBus.$on('search', (data) => {
      this.fetch(data);
    });
  }

  dataRender = (list) => {
    return this.props.dataRender ? this.props.dataRender(list) : list;
  };
  /**
   * 开始请求
   */
  handler = async () => {
    const isPost = this.props.post;
    const type = isPost ? '$request/post' : '$request/get';
    const data = isPost ? 'data' : 'params';

    const param = JSON.parse(JSON.stringify(this.state.params));
    Object.keys(param).forEach((k) => {
      if (!param[k] && param[k] !== 0) delete param[k];
    });
    param.pageNum = param.pageNum || 1;
    // 开始请求
    let res = await request(this.props.source, {
      method: 'POST',
      data: param,
    });
    const { total, pageSize, list } = res;
    this.setState((prevState) => ({
      dataSource: this.dataRender(list),
      pagination: {
        ...pageBaseConifg,
        pageSize: pageSize,
        total: total,
      },
    }));

    this.setState({ loading: false });
  };

  /**
   * 准备开始请求
   * @param {*} params
   */
  fetch = (params) => {
    this.setState(
      (prevState) => ({
        loading: true,
        params: { ...prevState.params, ...params },
      }),
      () => {
        this.handler();
      },
    );
  };
  getPage = () => {
    const { params } = this.state;
    return {
      pageNum: params.pageNum,
      pageSize: params.pageSize,
    };
  };
  getColumns = () => {
    let { columns } = this.props;
    const { showOrder, align } = this.props;
    if (showOrder) columns = [COLUMN_ORDER, ...columns];
    return columns.map((col) => {
      const ret = { ...col, align: col.align || align };
      if (!col.editable) return ret;
      return {
        ...ret,
        onCell: (record) => ({
          record,
          type: col.editable.type,
          dataIndex: col.dataIndex,
          title: col.title,
          editing: this.isEditing(record),
          options: col.editable.options,
          config: col.editable.config,
          cprops: col.editable.compProps,
        }),
      };
    });
  };

  getDataList = () => this.state.dataSource;

  isEditing = (record) => record[this.props.rowKey] === this.props.editingKey;

  render() {
    const { loading, dataSource, pagination, handleTableChange } = this.state;
    const { rowKey, tableProps, dataSource: dataSourceProps, form, style } = this.props;
    const components = { body: { cell: EditableCell } };
    return (
      <EditableContext.Provider value={form}>
        <div className={styles.tableList} style={style}>
          <Table
            components={components}
            bordered
            rowKey={rowKey}
            tableLayout="fixed"
            pagination={pagination}
            loading={loading}
            dataSource={dataSourceProps || dataSource || []}
            columns={this.getColumns()}
            onChange={handleTableChange}
            {...tableProps}
          >
            {this.props.children}
          </Table>
        </div>
      </EditableContext.Provider>
    );
  }
}
export default TableList;
